package study_elasticSearch;

import com.alibaba.fastjson2.JSONObject;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

public class CRUDDocument {
    public static void main(String[] args) {
        RestHighLevelClient client = null;
        try {
            //初始化
            CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
            credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("elastic", "VjFqg*_dOeNkth275zoG"));

            client = new RestHighLevelClient(RestClient.builder(new HttpHost("127.0.0.1", 9200, "http"))
                    .setHttpClientConfigCallback(httpClientBuilder -> httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider))
            );

            String id = "36934";
            JSONObject jsonObject = queryHotelById(id);
            System.out.println("------查询数据库结果：" + jsonObject);

            //向es新增文档
//            createDoc(id, jsonObject, client);

            //查询文档
//            getDoc(id, client);

            //修改文档
//            updateDoc(id, client);

            //删除文档
//            deleteDoc(id, client);

            //批量导入文档
            batchCreatDoc(client);

        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                if (null != client) {
                    //关闭
                    client.close();
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

    /**
     * 批量新增文档
     */
    private static void batchCreatDoc(RestHighLevelClient client) throws IOException {
        List<JSONObject> jsonObjects = queryAllHotel();
        BulkRequest bulkRequest = new BulkRequest();
        for (JSONObject jsObj : jsonObjects) {
            String _id = jsObj.getString("id");
            IndexRequest indexRequest = new IndexRequest(Constant.INDEX)
                    .id(_id)
                    .source(jsObj.toJSONString(), XContentType.JSON);
            bulkRequest.add(indexRequest);
        }
        BulkResponse bulkResponse = client.bulk(bulkRequest, RequestOptions.DEFAULT);
        System.out.println("批量新增文档结果：" + bulkResponse);
    }

    /**
     * 删除文档
     *
     * @param id 文档id
     */
    private static void deleteDoc(String id, RestHighLevelClient client) throws IOException {
        DeleteRequest deleteRequest = new DeleteRequest(Constant.INDEX, id);
        DeleteResponse deleteResponse = client.delete(deleteRequest, RequestOptions.DEFAULT);
        System.out.println("删除文档结果：" + deleteResponse);
    }

    /**
     * 局部更新文档
     *
     * @param id 文档id
     */
    private static void updateDoc(String id, RestHighLevelClient client) throws IOException {
        UpdateRequest updateRequest = new UpdateRequest(Constant.INDEX, id);
        updateRequest.doc(
                "newField", "123",
                "newField1", "123"
        );
        UpdateResponse updateResponse = client.update(updateRequest, RequestOptions.DEFAULT);
        System.out.println("修改结果：" + updateResponse);
    }

    /**
     * 查询文档
     *
     * @param id 文档id
     */
    private static void getDoc(String id, RestHighLevelClient client) throws IOException {
        GetRequest getRequest = new GetRequest(Constant.INDEX, id);
        GetResponse getResponse = client.get(getRequest, RequestOptions.DEFAULT);
        String doc = getResponse.getSourceAsString();
        System.out.println("------查询文档结果：" + doc);
    }

    /**
     * 创建文档
     *
     * @param id         文档id
     * @param jsonObject 文档对象
     */
    private static void createDoc(String id, JSONObject jsonObject, RestHighLevelClient client) throws IOException {
        IndexRequest indexRequest = new IndexRequest(Constant.INDEX).id(id);
        indexRequest.source(jsonObject.toJSONString(), XContentType.JSON);
        client.index(indexRequest, RequestOptions.DEFAULT);
        System.out.println("------新增文档完成------");
    }

    private static JSONObject queryHotelById(String id) {
        // 数据库连接信息
        String url = "jdbc:mysql://localhost:3306/study"; // 替换为你的数据库名称
        String username = "root"; // 替换为你的数据库用户名
        String password = "xxxx9999"; // 替换为你的数据库密码

        Connection connection = null;
        Statement statement = null;
        ResultSet resultSet = null;

        try {
            // 1. 加载 MySQL JDBC 驱动
            Class.forName("com.mysql.cj.jdbc.Driver");

            // 2. 建立数据库连接
            connection = DriverManager.getConnection(url, username, password);

            // 3. 创建 Statement 对象
            statement = connection.createStatement();

            // 4. 执行 SQL 查询
            String sql = "SELECT * FROM tb_hotel where id = '" + id + "'"; // 替换为你的表名
            resultSet = statement.executeQuery(sql);

            // 5. 处理查询结果
            if (resultSet.next()) {
                int _id = resultSet.getInt("id");
                String name = resultSet.getString("name");
                String address = resultSet.getString("address");
                int price = resultSet.getInt("price");
                int score = resultSet.getInt("score");
                String brand = resultSet.getString("brand");
                String city = resultSet.getString("city");
                String star_name = resultSet.getString("star_name");
                String business = resultSet.getString("business");
                String latitude = resultSet.getString("latitude");
                String longitude = resultSet.getString("longitude");
                String pic = resultSet.getString("pic");

                JSONObject jsonObject = new JSONObject();
                jsonObject.put("id", _id);
                jsonObject.put("name", name);
                jsonObject.put("address", address);
                jsonObject.put("price", price);
                jsonObject.put("score", score);
                jsonObject.put("brand", brand);
                jsonObject.put("city", city);
                jsonObject.put("star_name", star_name);
                jsonObject.put("business", business);
                jsonObject.put("latitude", latitude);
                jsonObject.put("longitude", longitude);
                jsonObject.put("pic", pic);

                return jsonObject;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 6. 关闭资源
            try {
                if (resultSet != null) resultSet.close();
                if (statement != null) statement.close();
                if (connection != null) connection.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return new JSONObject();
    }

    private static List<JSONObject> queryAllHotel() {
        ArrayList<JSONObject> res = new ArrayList<>();
        // 数据库连接信息
        String url = "jdbc:mysql://localhost:3306/study"; // 替换为你的数据库名称
        String username = "root"; // 替换为你的数据库用户名
        String password = "xxxx9999"; // 替换为你的数据库密码

        Connection connection = null;
        Statement statement = null;
        ResultSet resultSet = null;

        try {
            // 1. 加载 MySQL JDBC 驱动
            Class.forName("com.mysql.cj.jdbc.Driver");

            // 2. 建立数据库连接
            connection = DriverManager.getConnection(url, username, password);

            // 3. 创建 Statement 对象
            statement = connection.createStatement();

            // 4. 执行 SQL 查询
            String sql = "SELECT * FROM tb_hotel";
            resultSet = statement.executeQuery(sql);

            // 5. 处理查询结果
            while (resultSet.next()) {
                int _id = resultSet.getInt("id");
                String name = resultSet.getString("name");
                String address = resultSet.getString("address");
                int price = resultSet.getInt("price");
                int score = resultSet.getInt("score");
                String brand = resultSet.getString("brand");
                String city = resultSet.getString("city");
                String star_name = resultSet.getString("star_name");
                String business = resultSet.getString("business");
                String latitude = resultSet.getString("latitude");
                String longitude = resultSet.getString("longitude");
                String pic = resultSet.getString("pic");

                JSONObject jsonObject = new JSONObject();
                jsonObject.put("id", _id);
                jsonObject.put("name", name);
                jsonObject.put("address", address);
                jsonObject.put("price", price);
                jsonObject.put("score", score);
                jsonObject.put("brand", brand);
                jsonObject.put("city", city);
                jsonObject.put("star_name", star_name);
                jsonObject.put("business", business);
                jsonObject.put("latitude", latitude);
                jsonObject.put("longitude", longitude);
                jsonObject.put("pic", pic);

                res.add(jsonObject);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 6. 关闭资源
            try {
                if (resultSet != null) resultSet.close();
                if (statement != null) statement.close();
                if (connection != null) connection.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return res;
    }
}








